package com.chy.blog_server.modular.system.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chy.blog_server.core.util.PageAndParamUtil;
import com.chy.blog_server.core.util.UploadFileUtil;
import com.chy.blog_server.core.util.UploadURLUtil;
import com.chy.blog_server.core.util.UserUtil;
import com.chy.blog_server.modular.system.entity.SysUser;
import com.chy.blog_server.modular.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：后台用户表 controller
 * 作者：chenhuiyan
 * 时间：2020/02/13 22:07
 */
@Controller
@RequestMapping(value = "/sys/user")
public class SysUserController {

    /**
     * 前缀
     */
    private static String PREFIX = "system/sysUser/";

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 首页
     * @return
     */
    @RequestMapping(value = "")
    public String index(){
        return PREFIX + "user";
    }

    /**
     * 查询列表
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try{
            Map<String, Object> params = PageAndParamUtil.getParams();
            List<Map<String, Object>> list = sysUserService.list(params); //获取数据列表
            Integer count = sysUserService.getCount(params); //获取总数
            res.put("code", 0);
            res.put("msg", "获取数据成功");
            res.put("count", count);
            res.put("data", list);
        }catch (Exception e){
            e.printStackTrace();
            res.put("code", 500);
            res.put("msg", "获取数据失败");
        }
        return res;
    }

    /**
     * 跳转添加页面
     * @return
     */
    @RequestMapping(value = "/add")
    public String add(){
        return PREFIX + "user_add";
    }

    /**
     * 跳转编辑页面
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(String id, Model model){
        model.addAttribute("id", id);
        return PREFIX + "user_edit";
    }

    /**
     * 保存
     * @param sysUser
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveData")
    @ResponseBody
    public Map<String, Object> saveData(SysUser sysUser, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try {
            if(StrUtil.isEmpty(sysUser.getId())){

                //判断帐号是否存在
                SysUser su = sysUserService.getOne(new QueryWrapper<SysUser>().eq("user_name", sysUser.getUserName()));
                if(su != null){
                    res.put("state", "500");
                    res.put("message", "该帐号已存在！");
                    return res;
                }

                sysUser.preInsert(request);
                sysUser.setPassword(SecureUtil.md5(sysUser.getPassword())); //加密
                //默认头像
                if(StrUtil.isEmpty(sysUser.getHeadPhoto())){
                    sysUser.setHeadPhoto("moren.jpg");
                }
                sysUserService.save(sysUser);
                res.put("state", "200");
                res.put("message", "添加成功");
            }else{
                sysUser.preUpdate(request);
                sysUserService.updateById(sysUser);
                res.put("state", "200");
                res.put("message", "修改成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "添加失败");
        }
        return res;
    }

    /**
     * 根据id查找信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/getInfoById")
    @ResponseBody
    public Map<String, Object> getInfoById(String id){
        Map<String, Object> res = new HashMap<>();
        try{
            res = sysUserService.getInfoById(id);
            res.put("state", "200");
            res.put("message", "获取成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "获取失败");
        }
        return res;
    }

    /**
     * 跳转修改密码页面
     * @return
     */
    @RequestMapping(value = "/onPassword")
    public String onPassword(String id, Model model){
        model.addAttribute("id", id);
        return PREFIX + "update_password";
    }

    /**
     * 修改密码
     * @param sysUser
     * @param request
     * @return
     */
    @RequestMapping(value = "/updatePassword")
    @ResponseBody
    public Map<String, Object> updatePassword(SysUser sysUser, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try {
            SysUser su = sysUserService.getById(sysUser.getId());
            su.setPassword(SecureUtil.md5(sysUser.getPassword()));
            su.preUpdate(request);
            sysUserService.updateById(su);
            res.put("state", "200");
            res.put("message", "修改成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "修改失败");
        }
        return res;
    }

    /**
     * 跳转修改状态页面
     * @return
     */
    @RequestMapping(value = "/onStatus")
    public String onStatus(String id, Model model){
        model.addAttribute("id", id);
        return PREFIX + "update_status";
    }

    /**
     * 修改帐号状态
     * @param sysUser
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateStatus")
    @ResponseBody
    public Map<String, Object> updateStatus(SysUser sysUser, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try {
            SysUser su = sysUserService.getById(sysUser.getId());
            su.setStatus(sysUser.getStatus());
            su.preUpdate(request);
            sysUserService.updateById(su);
            res.put("state", "200");
            res.put("message", "修改成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "修改失败");
        }
        return res;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, Object> delete(String id){
        Map<String, Object> res = new HashMap<>();
        try{

            //判断是否为管理员
            SysUser sysUser = sysUserService.getById(id);
            if("admin".equals(sysUser.getUserName())){
                res.put("state", "500");
                res.put("message", "不能删除超级管理员");
                return res;
            }

            sysUserService.removeById(id);
            res.put("state", "200");
            res.put("message", "删除成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "删除失败");
        }
        return res;
    }

    /**
     * 管理员资料修改页面
     * @return
     */
    @RequestMapping(value = "/user_setting_index")
    public String user_setting_index(){
        return PREFIX + "user_setting";
    }

    /**
     * 修改资料
     * @param sysUser
     * @param request
     * @return
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(SysUser sysUser, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try{
            SysUser user = UserUtil.getUserFromSession(request);
            user.setUserName(sysUser.getUserName());
            user.setNickName(sysUser.getNickName());
            user.setSex(sysUser.getSex());
            user.setStatus(sysUser.getStatus());
            user.preUpdate(request);
            sysUserService.updateById(user);
            UserUtil.updateUserInSession(request, user);
            res.put("state", "200");
            res.put("message", "修改成功");
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "修改失败");
        }
        return res;
    }

    /**
     * 修改密码页面
     * @return
     */
    @RequestMapping(value = "/set_password_index")
    public String set_password_index(){
        return PREFIX + "user_password";
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "/setPassword")
    @ResponseBody
    public Map<String, Object> setPassword(String oldPassword, String newPassword, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try{
            SysUser sysUser = UserUtil.getUserFromSession(request);

            if(SecureUtil.md5(oldPassword).equals(sysUser.getPassword())){ //校验旧密码是否一致
                //修改
                SysUser user = sysUserService.getById(sysUser.getId());
                user.setPassword(SecureUtil.md5(newPassword));
                user.preUpdate(request);
                sysUserService.updateById(user);

                UserUtil.removeUserIntoSession(request); //清除session

                res.put("state", "200");
                res.put("message", "密码修改成功");
            }else{
                res.put("state", "500");
                res.put("message", "原密码错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            res.put("state", "500");
            res.put("message", "密码修改失败");
        }
        return res;
    }

    /**
     * 上传头像
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadHeadPhoto")
    @ResponseBody
    public Map<String, Object> uploadHeadPhoto(MultipartFile file, HttpServletRequest request){
        //获取登录用户信息
        SysUser loginUser = UserUtil.getUserFromSession(request);

        //上传
        Map<String, Object> res = UploadFileUtil.fileUploadToOne(file, UploadURLUtil.HEAD_PHOTO, false);

        //根据id查询用户
        SysUser sysUser = sysUserService.getById(loginUser.getId());

        if("200".equals(res.get("state"))){
            sysUser.setHeadPhoto(res.get("fileName") + "");
            sysUser.preUpdate(request);
            sysUserService.updateById(sysUser); //更新
            UserUtil.updateUserInSession(request, sysUser); //更新session
        }

        return res;
    }

}
